﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Web;
using System.Net;

namespace Daneas.Utility.Universals
{
    public class FileHelper
    {

        /// <summary>
        /// 将错误日志写入日志文件（.txt,.log）
        /// </summary>
        /// <param name="path">日志文件路径</param>
        /// <param name="msg">错误日志</param>
        /// <returns></returns>
        public static bool WriteToLog(string path, string msg)
        {
            try
            {
                string detail = File.ReadAllText(path);

                detail += "=======================================================================================\r\n";
                detail += msg + "\r\n";

                File.WriteAllText(path, detail);

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool SaveToLocal(string sourcePath, string localPath)
        {
            System.Net.WebClient webClient = new System.Net.WebClient();

            webClient.Credentials = System.Net.CredentialCache.DefaultCredentials;

            webClient.DownloadFile(sourcePath, "c:\\DownLoad");

            return true;
        }

        /// <summary>
        /// 压缩图片(质量)
        /// </summary>
        /// <param name="sFile"></param>
        /// <param name="outPath"></param>
        /// <param name="flag">1-100，越小越压缩</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(string sFile, string outPath, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);

            ImageFormat tFormat = iSource.RawFormat;
            //以下代码为保存图片时，设置压缩质量 
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100 
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径 
                }
                else
                {

                    iSource.Save(outPath, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
            }
        }

        /// <summary>  
        /// 为图片生成缩略图(大小）    
        /// </summary>  
        /// <param name="image">图片</param>  
        /// <param name="width">缩略图宽</param>  
        /// <param name="height">缩略图高</param>  
        /// <returns></returns>  
        public static System.Drawing.Image GetThumbnail(System.Drawing.Image image, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);

            //从Bitmap创建一个System.Drawing.Graphics  
            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);

            //设置   
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //下面这个也设成高质量  
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

            //下面这个设成High  
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            //把原始图像绘制成上面所设置宽高的缩小图  
            System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height);

            gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            return bmp;
        }

        /// <summary>  
        /// 为图片生成缩略图    （大小）
        /// </summary>  
        /// <param name="imgpath">原图片的路径</param>  
        /// <param name="width">缩略图宽</param>  
        /// <param name="height">缩略图高</param>  
        /// <returns></returns>  
        public System.Drawing.Image GetThumbnail(string imgpath, int width, int height)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(imgpath), true);

            return GetThumbnail(image, width, height);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="from">物理路径</param>
        /// <param name="to"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static bool GetSmallPic(string from, string to, int width)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(from, true);

                int height = 0;

                double rate = width * 1.00 / image.Width;
                if (rate < 1)
                {
                    height = Convert.ToInt32(image.Height * rate);
                }
                else
                {
                    height = image.Height;
                }

                Image newone = GetThumbnail(image, width, height);

                ImageFormat tFormat = image.RawFormat;


                to = HttpContext.Current.Server.MapPath(to);

                newone.Save(to, tFormat);

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 从图片地址下载图片到本地磁盘
        /// </summary>
        /// <param name="ToLocalPath">图片本地磁盘地址</param>
        /// <param name="Url">图片网址</param>
        /// <returns></returns>
        public static bool DownWebImg(string FileName, string Url)
        {
            bool Value = false;

            WebResponse response = null;

            Stream stream = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

                response = request.GetResponse();

                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);

                }

            }
            catch (Exception err)
            {
                string aa = err.ToString();
            }
            return Value;
        }

        /// <summary>
        /// 将二进制文件保存到磁盘
        /// </summary>
        /// <param name="response">The response used to save the file</param>       
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;

            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                {
                    File.Delete(FileName);
                }

                Stream outStream = System.IO.File.Create(FileName);

                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);

                    if (l > 0)
                    {
                        outStream.Write(buffer, 0, l);
                    }
                }
                while (l > 0);

                outStream.Close();

                inStream.Close();
            }
            catch
            {
                Value = false;
            }

            return Value;
        }
    }
}
